import { defineStore, storeToRefs } from 'pinia';
import { isNull, isNumber, isUndefined } from '../core/is';
import { Chapter } from '../core/book/book';
import { BookSource } from '../core/plugins/defined/booksource';
import { nanoid, chunkArray, errorHandler, newError } from '../core/utils';
import { useDetailStore } from './detail';
import { useSettingsStore } from './settings';
import { useMessage } from '../hooks/message';
import { useBookshelfStore } from './bookshelf';
import { useTextContentStore } from './text-content';
import { EventCode } from '../../events';

// 下载任务状态
export enum DownloadStatus {
  WAITING = 'waiting',
  DOWNLOADING = 'downloading',
  COMPLETED = 'completed',
  FAILED = 'failed',
  PAUSED = 'paused'
}

// 下载任务类型
export interface DownloadTask {
  id: string;
  pid: string;
  detailUrl: string;
  bookname: string;
  author: string;
  coverImageUrl?: string;
  totalChapters: number;
  downloadedChapters: number;
  status: DownloadStatus;
  progress: number;
  error?: string;
  startTime?: number;
  endTime?: number;
  chapters: Chapter[];
}

// 导出格式
export enum ExportFormat {
  TXT = 'txt',
  EPUB = 'epub' // 未来可以支持更多格式
}

export const useDownloadStore = defineStore('Download', {
  state: () => ({
    tasks: [] as DownloadTask[],
    runningTasks: 0,
    maxConcurrentTasks: 2, // 最大并发下载任务数
  }),

  persist: {
    key: 'readcat-download-tasks',
    storage: window.localStorage,
    paths: ['tasks', 'maxConcurrentTasks'],
    // 序列化时排除运行中的任务状态
    serializer: {
      serialize: (state) => {
        // 在保存状态前，将正在下载的任务转换为暂停状态
        const serializedState = JSON.parse(JSON.stringify(state));
        serializedState.tasks.forEach((task: any) => {
          if (task.status === DownloadStatus.DOWNLOADING) {
            task.status = DownloadStatus.PAUSED;
          }
        });
        return JSON.stringify(serializedState);
      },
      deserialize: (value) => JSON.parse(value),
    },
  },

  getters: {
    activeTasks: (state) => state.tasks.filter(task => task.status === DownloadStatus.DOWNLOADING || task.status === DownloadStatus.WAITING),
    completedTasks: (state) => state.tasks.filter(task => task.status === DownloadStatus.COMPLETED),
    failedTasks: (state) => state.tasks.filter(task => task.status === DownloadStatus.FAILED),
    pausedTasks: (state) => state.tasks.filter(task => task.status === DownloadStatus.PAUSED),
  },

  actions: {
    // 初始化下载管理器
    initialize() {
      // 注册应用启动事件
      EventCode.onApplicationStart(() => {
        // 应用启动时，重新计算runningTasks
        this.runningTasks = this.tasks.filter(task => task.status === DownloadStatus.DOWNLOADING).length;
        
        // 自动启动等待中的任务
        this.startNextTask();
      });
      
      // 注册应用关闭事件
      EventCode.onApplicationClose(() => {
        // 应用关闭前，暂停所有下载任务
        this.tasks.forEach(task => {
          if (task.status === DownloadStatus.DOWNLOADING) {
            this.pauseDownloadTask(task.id);
          }
        });
      });
    },
    
    // 添加下载任务
    async addDownloadTask(pid: string, detailUrl: string, bookname: string, author: string, coverImageUrl?: string): Promise<void> {
      try {
        const detailStore = useDetailStore();
        
        // 先获取书籍详情
        if (!detailStore.detailResult || detailStore.detailResult.detailPageUrl !== detailUrl || detailStore.detailResult.pid !== pid) {
          await detailStore.getDetailPage(pid, detailUrl);
        }

        if (!detailStore.detailResult || detailStore.detailResult.chapterList.length === 0) {
          throw newError('无法获取章节列表');
        }

        const task: DownloadTask = {
          id: nanoid(),
          pid,
          detailUrl,
          bookname,
          author,
          coverImageUrl,
          totalChapters: detailStore.detailResult.chapterList.length,
          downloadedChapters: 0,
          status: DownloadStatus.WAITING,
          progress: 0,
          chapters: detailStore.detailResult.chapterList,
        };

        this.tasks.unshift(task);
        useMessage().success(`已添加《${bookname}》到下载队列`);
        
        // 自动开始下载任务
        this.startNextTask();
      } catch (e) {
        useMessage().error(errorHandler(e, true));
        throw e;
      }
    },

    // 更新最大并发任务数
    updateMaxConcurrentTasks(count: number): void {
      if (count < 1) {
        count = 1;
      } else if (count > 10) {
        count = 10;
      }
      
      this.maxConcurrentTasks = count;
      useMessage().success(`已设置最大并发下载任务数为 ${count}`);
      
      // 如果有等待中的任务，尝试启动更多任务
      this.startNextTask();
    },

    // 开始下一个等待中的任务
    async startNextTask(): Promise<void> {
      if (this.runningTasks >= this.maxConcurrentTasks) {
        return;
      }

      const waitingTask = this.tasks.find(task => task.status === DownloadStatus.WAITING);
      if (!waitingTask) {
        return;
      }

      this.runningTasks++;
      await this.startDownloadTask(waitingTask.id);
    },

    // 开始指定的下载任务
    async startDownloadTask(taskId: string): Promise<void> {
      const task = this.tasks.find(t => t.id === taskId);
      if (!task) {
        throw newError('任务不存在');
      }

      if (task.status === DownloadStatus.DOWNLOADING) {
        return;
      }

      task.status = DownloadStatus.DOWNLOADING;
      task.startTime = task.startTime || Date.now();
      task.downloadedChapters = 0;
      task.progress = 0;
      task.error = undefined;

      try {
        const { threadsNumber } = storeToRefs(useSettingsStore());
        const booksource = GLOBAL_PLUGINS.getPluginInstanceById<BookSource>(task.pid);
        
        if (!booksource) {
          throw newError(`无法获取书源插件, 插件ID:${task.pid}`);
        }

        // 分批次下载章节
        const chunks = chunkArray(task.chapters, threadsNumber.value);
        for (const chunk of chunks) {
          // 检查任务状态，如果是暂停则退出下载循环
          if (task.status === DownloadStatus.PAUSED) {
            return;
          }

          const promises = chunk.map(async (chapter) => {
            try {
              // 先检查是否已经缓存
              const cached = await GLOBAL_DB.store.textContentStore.getByPidAndChapterUrl(task.pid, chapter.url);
              if (!cached) {
                // 下载章节内容
                const textContent = await booksource.getTextContent(chapter);
                
                // 保存到数据库
                await GLOBAL_DB.store.textContentStore.put({
                  id: nanoid(),
                  pid: task.pid,
                  detailUrl: task.detailUrl,
                  chapter,
                  textContent,
                });
              }
              
              // 更新进度
              task.downloadedChapters++;
              task.progress = Math.round((task.downloadedChapters / task.totalChapters) * 100);
            } catch (e) {
              GLOBAL_LOG.error(`下载章节失败: ${chapter.title}`, e);
              // 不中断整体下载，但记录失败
            }
          });

          await Promise.allSettled(promises);
        }

        // 下载完成
        task.status = DownloadStatus.COMPLETED;
        task.endTime = Date.now();
        useMessage().success(`《${task.bookname}》下载完成`);
      } catch (e) {
        task.status = DownloadStatus.FAILED;
        task.error = errorHandler(e, true);
        useMessage().error(`下载《${task.bookname}》失败: ${task.error}`);
        GLOBAL_LOG.error(`下载任务失败: ${task.bookname}`, e);
      } finally {
        this.runningTasks--;
        // 开始下一个任务
        this.startNextTask();
      }
    },

    // 暂停下载任务
    pauseDownloadTask(taskId: string): void {
      const task = this.tasks.find(t => t.id === taskId);
      if (task && task.status === DownloadStatus.DOWNLOADING) {
        task.status = DownloadStatus.PAUSED;
        useMessage().info(`已暂停《${task.bookname}》的下载`);
      }
    },

    // 取消下载任务
    cancelDownloadTask(taskId: string, removeFromList: boolean = false): void {
      const taskIndex = this.tasks.findIndex(t => t.id === taskId);
      if (taskIndex !== -1) {
        const task = this.tasks[taskIndex];
        const wasDownloading = task.status === DownloadStatus.DOWNLOADING;
        
        if (wasDownloading) {
          this.runningTasks--;
          
          if (removeFromList) {
            this.tasks.splice(taskIndex, 1);
          } else {
            task.status = DownloadStatus.FAILED;
            task.error = '已取消下载';
          }
        } else {
          this.tasks.splice(taskIndex, 1);
        }
        
        // 如果是正在下载的任务被取消，启动下一个任务
        if (wasDownloading && !removeFromList) {
          this.startNextTask();
        }
        
        useMessage().info(`已取消《${task.bookname}》的下载`);
      }
    },

    // 导出已下载的书籍
    async exportBook(pid: string, detailUrl: string, format: ExportFormat = ExportFormat.TXT): Promise<void> {
      try {
        const detailStore = useDetailStore();
        
        // 确保书籍详情已加载
        if (!detailStore.detailResult || detailStore.detailResult.detailPageUrl !== detailUrl || detailStore.detailResult.pid !== pid) {
          await detailStore.getDetailPage(pid, detailUrl);
        }

        if (!detailStore.detailResult) {
          throw newError('无法获取书籍详情');
        }

        const { bookname, author, chapterList } = detailStore.detailResult;
        let content = `${bookname}\n作者：${author}\n\n`;

        // 逐章获取内容
        for (const chapter of chapterList) {
          const cached = await GLOBAL_DB.store.textContentStore.getByPidAndChapterUrl(pid, chapter.url);
          if (cached) {
            content += `\n${chapter.title}\n`;
            content += cached.textContent.join('\n');
            content += '\n';
          }
        }

        // 根据格式导出
        if (format === ExportFormat.TXT) {
          const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `${bookname}_${author}.txt`;
          document.body.appendChild(a);
          a.click();
          // 清理
          setTimeout(() => {
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
          }, 0);
        }
        
        useMessage().success(`《${bookname}》导出成功`);
      } catch (e) {
        useMessage().error(errorHandler(e, true));
        throw e;
      }
    },

    // 检查书籍是否已完全下载
    async isBookFullyDownloaded(pid: string, detailUrl: string): Promise<boolean> {
      try {
        const detailStore = useDetailStore();
        let chapterList = [];
        
        // 先尝试从现有任务中获取章节列表，避免重复加载
        const existingTask = this.tasks.find(task => task.pid === pid && task.detailUrl === detailUrl);
        if (existingTask && existingTask.chapters && existingTask.chapters.length > 0) {
          chapterList = existingTask.chapters;
        } else {
          // 再尝试从detailStore获取
          if (!detailStore.detailResult || detailStore.detailResult.detailPageUrl !== detailUrl || detailStore.detailResult.pid !== pid) {
            await detailStore.getDetailPage(pid, detailUrl);
          }

          if (!detailStore.detailResult) {
            return false;
          }

          chapterList = detailStore.detailResult.chapterList;
        }

        if (chapterList.length === 0) {
          return false;
        }
        
        // 检查每一章是否都已缓存
        for (const chapter of chapterList) {
          const cached = await GLOBAL_DB.store.textContentStore.getByPidAndChapterUrl(pid, chapter.url);
          if (!cached || cached.textContent.length === 0) {
            return false;
          }
        }

        return true;
      } catch (e) {
        GLOBAL_LOG.error('检查书籍下载状态失败', e);
        return false;
      }
    },
  },
});